<?php
class htsdk
{
    private $app_id;
    private $app_secret;
    private $api_url;

    public function __construct($app_id = '', $app_secret = '')
    {
        $this->app_id = $app_id;
        $this->app_secret = $app_secret;
        $this->api_url = 'https://m.huitui.fun/api/v1';
    }

    /**
     * 执行任务
     * @param string $task_id 任务ID
     * @param float $pay_price 实际支付金额
     * @param string $payment 支付方式
     * @return mixed
     */
    public function execute($task_id, $pay_price, $payment)
    {
        $data = [
            'app_id' => $this->app_id, // 商户app_id
            'task_id' => $task_id, // 任务ID
            'pay_price' => $pay_price, // 实际支付金额
            'payment' => $payment, // 支付方式
            'time' => time(),
        ];
        $data['sign'] = $this->getSign($data, $this->app_secret);
        $res = $this->httpGet($this->api_url, $data);
        return json_decode($res, true);
    }

    private function httpGet($url, $data)
    {
        $url = $url . '?' . http_build_query($data);
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }

    private function getSign($data, $secret) {
        if ( isset($data['sign']) ) {
            unset($data['sign']);
        }
        // 对数组的值按key排序
        ksort($data);
        // 生成url的形式
        $params = http_build_query($data);
        // 生成sign
        $sign = strtolower(md5($params . $secret));
        return $sign;
    }
}